package com.soul.dj.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.soul.dj.MainApplication;
import com.soul.dj.ui.activity.LoginActivity;
import com.soul.dj.util.http.*;
import com.soul.dj.util.http.json.JsonProcessUtil;
import okhttp3.*;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public abstract  class BaseFragment extends Fragment implements OnClickListener{

	private OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
			.connectTimeout(60, TimeUnit.SECONDS)      //设置连接超时
			.readTimeout(60, TimeUnit.SECONDS)         //设置读超时
			.writeTimeout(60, TimeUnit.SECONDS)        //设置写超时
			.retryOnConnectionFailure(true)            //是否自动重连
			.build();;
	protected FragmentActivity activity;
	protected static final String TAG = Package.class.getName();
	private Dialog dialog;

	private boolean progressEnabled = true;


	public void setProgressEnabled(boolean progressEnabled) {
		this.progressEnabled = progressEnabled;
	}



	public boolean httpPrepare(String tag) {
		boolean avl = NetWorkUtils.isNetworkAvailable(activity);

		if (!avl) {
			closeDialog();
			// this.onAjaxError("您的手机网络已断开，请连接后重试。", tag);
			AlertDialogUitls.alert(activity,"提示", "您的手机网络已断开，请连接后重试。", new String[] { "确定" },
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							MainApplication.exit();
							System.exit(0);
						}
					});
		}

		return avl;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected void sendHttp(Constants.HTTP method, String url, RequestBody params,
							JSONCallBack callback) {
		if (!httpPrepare("")) {
			return;
		}
		showDialog();
		Request request = null;
		if (method == Constants.HTTP.GET) {
			request = new Request.Builder().url(url) .get().build();
		} else if (method == Constants.HTTP.POST) {
			request = new Request.Builder().url(url) .post(params).build();
		}
		//3,创建一个call对象
		Call call = mOkHttpClient.newCall(request);
		//4,将请求添加到调度中
		call.enqueue(callback);

	}

	@SuppressWarnings("rawtypes")
	protected void sendHttp(String url, okhttp3.MediaType mediaype, Map<String,Object> paramsMap,
							JSONCallBack callback) {
		Log.d("soul", activity+"----");
		if (!httpPrepare("")) {
			return;
		}
		try{
			Log.d("HttpProcessor:",
					"请求url:" + url + "\n请求参数:" + JsonProcessUtil.beanToJson(paramsMap));
			RequestBody body = RequestBody.create(mediaype, JsonProcessUtil.beanToJson(paramsMap));
			sendHttp(Constants.HTTP.POST, url, body, callback);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	protected void sendHttpFiles(String url, okhttp3.MediaType mediaype, Map<String,Object> paramsMap,String fileKey, List<String> fileList, JSONCallBack callback) {
		if (!httpPrepare("")) {
			return;
		}
		try{
			Log.d("HttpProcessor:",
					"请求url:" + url + "\n请求参数:" + JsonProcessUtil.beanToJson(paramsMap)+JsonProcessUtil.beanToJson(fileList));

			RequestBody body = RequestBody.create(mediaype, JsonProcessUtil.beanToJson(paramsMap));

			MultipartBody.Builder buider = new MultipartBody.Builder().setType(MultipartBody.FORM);
			for (String path : fileList ) {
				File file = new File("file://"+path);
				RequestBody fileBody = RequestBody.create(com.soul.dj.util.http.MediaType.getMimeType(file.getName()) , file);
				buider.addFormDataPart(fileKey , file.getName() , fileBody);
			}
			buider.addPart(body);

			sendHttp(Constants.HTTP.POST, url,buider.build(), callback);
		}catch (Exception e){
			e.printStackTrace();
			Log.e("yhbsoul",e.getMessage());
		}
	}

	public void onErrorDialogClick() {

	}
	/**
	 * 显示Dialog
	 */
	private void showDialog() {
		if (progressEnabled) {
			if (dialog == null) {
				dialog = LoadingDialog.createLoadingDialog(activity, "正在加载中...");
				dialog.show();
			}
		}
	}

	/**
	 * 关闭Dialog
	 */
	private void closeDialog() {
		if (progressEnabled) {
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}
		}
	}


	protected DialogInterface.OnClickListener errorDialogClicklistener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
			onErrorDialogClick();
		}
	};

	public void onAjaxError(String tag) {

		closeDialog();
		AlertDialogUitls.alert(activity,"提示", "数据加载异常，请确认您的手机网络畅通！", new String[] { "确定" },
				errorDialogClicklistener);
	}
	
	protected void showKeyboard() {
		View v = activity.getCurrentFocus();

		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);

		if (imm != null && v != null) {

			imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);

		}
	}

	protected void hideKeyboard() {
		View v = activity.getCurrentFocus();

		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);

		if (imm != null && v != null) {

			imm.hideSoftInputFromWindow(v.getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);

		}
	}

	public void onAjaxFail(String code,String title, String str, String tag) {
		Looper.prepare();
		if (TextUtils.equals(code,"-200")){
			startActivity(new Intent(activity, LoginActivity.class));
			MainApplication.clearMap();
			MainApplication.removeActivity(activity);
		}else{
			toast(str);
		}
	}


	public void onAjaxOK(Object result, String tag) {
		closeDialog();
    }



	protected void toast(String msg) {
		Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
}
